$m(function(args) {
	var that = this;
	var $this = this.element;
	var pageUrl = args.pageUrl;
	var resourceId = args.subjectId;
	var workSpaceId = args.workSpaceId;
	var workSpaceType = args.workSpaceType;
	/**
	 * 已选列表
	 */
	var grid = $this.find("#tempo-resouce-permission-grid");
	
	/**
	 * 初始化
	 */
	var init = function(){
		if(workSpaceType=="self"){
			renderSelfGrid(workSpaceType);
		}else{
			renderGrid(workSpaceType);
		}
	}
	
	
	var  renderSelfGrid =function(workSpaceType){
		var rqId = resourceId;
		if(resourceId.endsWith(".model")){
			var rqStr = resourceId.substring(0,resourceId.length-6);
			rqId = rqStr.split(",")[0];
		}
		grid.datagrid({
			url : contextPath+"/api/ai/resource/permission/list-users",
			datatype:'json',
			type : 'post',
			fit : true, 
			rownumbers : true,
			colNames:getselfColName(),
			colModel:getselfColModel(),
			rowNum:1000,
			pagination:false,
			multiselect : true, 
			postData:{
				resourceId : rqId,
				name : ''
			},
			jsonReader : {
				root : 'data'
			},
			sortable:false,
			searchBar:true,
			searchBarOptions:{
				placeholder:'请输入用户名称或编码',
				onSearch:function(value){
					grid.datagrid("reloadGrid",{name:value},true);
				} 
			},
			toolbar:getToolbar(workSpaceType)
		});
	}
	/**
	 * 绘制人员列表 
	 * 15所项目传过来的id以model结尾
	 */
	var renderGrid = function(workSpaceType){
		var rqId = resourceId;
		if(resourceId.endsWith(".model")){
			var rqStr = resourceId.substring(0,resourceId.length-6);
			rqId = rqStr.split(",")[0];
		}
		grid.datagrid({
			url : contextPath+"/api/ai/resource/permission/list-users",
			datatype:'json',
			type : 'post',
			fit : true, 
			rownumbers : true,
			colNames:getColName(),
			colModel:getColModel(),
			rowNum:1000,
			pagination:false,
			multiselect : true,
			postData:{
				resourceId : rqId,
				workSpaceId:workSpaceId,
				name:''
			},
			jsonReader : {
				root : 'data'
			},
			loadComplete:function(data){
				$('div[ui-role=switchbutton]').each(function(){
					$(this).switchbutton({open:$(this).attr('open')});
					if($(this).attr('value')=='manager'){
						$(this).switchbutton('disable');
					}
				})
			},
			sortable:false,
			searchBar:true,
			searchBarOptions:{
				placeholder:'请输入用户名称或编码',
				onSearch:function(value){
					grid.datagrid("reloadGrid",{name:value},true);
				} 
			},
			toolbar:getToolbar(workSpaceType)
		});
	}
	
	/**
	 * 列名称
	 */
	var getColName = function(){
		var names = ["id",TempoUtils.locale("bidesign.username"),TempoUtils.locale("bidesign.usercode"),TempoUtils.locale("bidesign.workspace_type"),TempoUtils.locale("bidesign.theme_auth"),"code"];
		return names;
	}
	
	/**
	 * 列名称
	 */
	var getselfColName = function(){
		var names = ["id",TempoUtils.locale("bidesign.username"),TempoUtils.locale("bidesign.usercode"),"code"];
		return names;
	}
	/**
	 * 列模型
	 */
	var getColModel = function(){
		var arr = [{
			name:'ID',
			id : true,
			hidden:true
		},{
			name:'NAME',
			sortable:false
		},{
			name:'USERCODE',
			sortable:false
		},{
			name:'TYPE',
			sortable:false,
			formatter : function(d) {
				return d=='1'?TempoUtils.locale("bidesign.workspace_perm_manage"):
					TempoUtils.locale("bidesign.workspace_perm_use");
			},
		},{
			name:'HASPRIVI',
			sortable:false,
			formatter : function(d) {
				var id=TempoUtils.uuid();
				if(d=='manager'){
					return "<div style='margin-left:65px' id='"+id+"' ui-role='switchbutton' value='manager' open=true ></div>";
				}
				return "<div style='margin-left:65px' id='"+id+"' ui-role='switchbutton' value='"+d+"' "+(d=='1'?'open=true':'')+" ></div>";
			},
		},{
			name:'CODE',
			hidden:true,
			sortable:false
		}];
		return arr;
	}
	
	
	/**
	 * 列模型
	 */
	var getselfColModel = function(){
		var arr = [{
			name:'ID',
			id : true,
			hidden:true
		},{
			name:'NAME',
			sortable:false
		},{
			name:'USERCODE',
			sortable:false
		},{
			name:'CODE',
			hidden:true,
			sortable:false
		}];
		return arr;
	}
	
	
	/**
	 * 工具条
	 */
	var getToolbar = function(workSpaceType){
		var toolbar;
		if(workSpaceType=="self"){
			toolbar = [
				{
					id : "add",
					text : TempoUtils.locale("bidesign.add"),
					click : function(e) {
						toolbarEvent["add"]();
					}
				},{
					id : "remove",
					text : TempoUtils.locale("bidesign.delete"),
					click : function(e) {
						toolbarEvent["remove"]();
					}
				}
			];
		} else {
			toolbar = [
				{
					id : "auth",
					text : TempoUtils.locale("aidsview.auth"),
					click : function(e) {
						toolbarEvent["auth"]();
					}
				},{
					id : "cancelauth",
					text : TempoUtils.locale("aidsview.cancelauth"),
					click : function(e) {
						toolbarEvent["cancelauth"]();
					}
				}
			];
		}
		return toolbar;
	}
	
	
	
	/**
	 * 工具条事件处理
	 */
	var toolbarEvent = {
		add:function(){
			var data = grid.datagrid('getRowData');
			var codes = [];
			if(data && data.length > 0){
				for(var i = 0;i<data.length;i++){
					codes.push(data[i].CODE);
				}
			}
			$("<div/>").userselect({
				isFilterCurrentUser:true,
				showRoleTree:true,
				showWorkgroupTree:true,
				showOrgTree:false,
				isSessionUserOrg:true,
				isSessionUserRole:true,
				isShowAllText:true,
				sessionUserOrgUrl: contextPath + '/api/sys/ou/org/list',
				listUserByOrgIdUrl:contextPath + '/api/sys/ou/user/list-designer-by-orgid',
				listUserByRoleIdUrl:contextPath + '/api/sys/ou/user/list-designer-by-roleid',
				listUserByWorkgroupIdUrl:contextPath + '/api/sys/ou/user/list-designer-by-groupid',
				codes:codes,
				orgUrlParam:{pid:""},
				saveHandler:function(data){
					saveSelectUser(data);
				}
			});
		},
		remove:function(){
			removeUserPermission();
		},
		auth : function () {
			authUsers();
		},
		cancelauth:function () {
			cancelAuthUsers();
		}
	}
	
	/**
	 * 选择用户进行权限配置
	 */
	var saveSelectUser = function(data){
		if(data && data.length > 0){
			var userIds = [];
			for (var i = 0; i < data.length; i++) {
				userIds.push(data[i].ID);
			}
			$.ajax({
				url: contextPath+"/api/ai/resource/permission/grant",
				method: 'POST',
				data: {
					resourceId : resourceId,
					users : userIds.join(',')
				},
				success: function(data) {
					grid.datagrid("reloadGrid");
					Eventbus.trigger("permission.theme",data);
				}
			})
		}
	}
	
	
	/**
	 * 新增人员回调
	 */
	var addUserCallback = function(){
		grid.datagrid("reloadGrid",{},true); 
	}
	
	/**
	 * 删除用户权限
	 */
	var removeUserPermission = function(){
		var selectRows = grid.datagrid("getSelectRowData");
		if(selectRows==null||selectRows.length==0){
			$("<div>").alert({
				msg : '请选择一条记录'
			});
			return;
		}
		
		var selectIds = [];
		var userCodes = [];
		for (var i = 0; i < selectRows.length; i++) {
			selectIds.push(selectRows[i].ID);
			userCodes.push(selectRows[i].CODE);
		}
		//15所删除权限入口
		if(resourceId.endsWith(".model")){
			$("<div/>").confirm({
				msg:'确定删除？',
				ok:function(){
					$.ajax({
						url: contextPath+"/api/flab/permission/revoke-by-id",
						data:{
							users : userCodes.join(','),
							resourceId : resourceId,
						},
						type:'post', 
						success:function(result){
							grid.datagrid("reloadGrid",{},true); 
						}
					});
				}
			});
			rqId = resourceId.split(",")[0];
		}else{
			$("<div/>").confirm({
				msg:'确定删除？',
				ok:function(){
					$.ajax({
						url: contextPath+"/api/ai/resource/permission/revoke-by-id",
						data:{
							ids : selectIds.join(','),
						},
						type:'post', 
						success:function(result){
							grid.datagrid("reloadGrid",{},true); 
							Eventbus.trigger("permission.theme",result);
						}
					});
				}
			});
		}
	}

	/***
	 * 授权
	 */
	var authUsers = function(){
		var selectRows = grid.datagrid("getSelectRowData");
		var selectRowsLength = selectRows.length;
		if(selectRows==null || selectRowsLength == 0){
			$("<div>").alert({
				msg : '请选择一条记录'
			});
			return;
		}
		var isNext = false;
		for (var i = 0; i < selectRows.length; i++) {
			if (selectRows[i].TYPE == '使用权限'){
				isNext = true;
				break;
			}
		}
		if (!isNext){
			return;
		}
		for (var i = 0; i < selectRowsLength; i++) {
			var id = $(selectRows[i].HASPRIVI)[0].id;
			if (selectRows[i].TYPE=='使用权限'){
				$('#'+id).switchbutton('setOpen',true);
			}
		}
	}

	/**
	 * 取消授权
	 * @constructor
	 */
	/**
	 * 取消授权
	 * @constructor
	 */
	var cancelAuthUsers = function(){
		var selectRows = grid.datagrid("getSelectRowData");
		var selectRowsLength = selectRows.length;
		if(selectRows == null || selectRowsLength==0){
			$("<div>").alert({
				msg : '请选择一条记录'
			});
			return;
		}
		var isNext = false;
		for (var i = 0; i < selectRows.length; i++) {
			if (selectRows[i].TYPE == '使用权限'){
				isNext = true;
				break;
			}
		}
		if (!isNext){
			return;
		}
		for (var i = 0; i < selectRowsLength; i++) {
			var id = $(selectRows[i].HASPRIVI)[0].id;
			if (selectRows[i].TYPE=='使用权限'){
				$('#'+id).switchbutton('setOpen',false);
			}
		}
	}
	
	init();
});	
	
